package com.shux.usermanager.biz.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shux.common.exception.ShuxRunTimeException;
import com.shux.usermanager.biz.ISysButtonPermissionBiz;
import com.shux.usermanager.biz.ISysRoleBiz;
import com.shux.usermanager.biz.ISysUserBiz;
import com.shux.usermanager.constant.UserConstant;
import com.shux.usermanager.dao.ISysUserDao;
import com.shux.usermanager.entity.SysButtonPermission;
import com.shux.usermanager.entity.SysRole;
import com.shux.usermanager.entity.SysUser;
import com.shux.utils.constants.Constant;
import com.shux.utils.page.PageData;

@Service("sysUserBiz")
public class SysUserBizImpl  implements ISysUserBiz {
    
    private @Autowired ISysUserDao sysUserDao;
    private @Autowired ISysRoleBiz sysRoleBiz;
    private @Autowired ISysButtonPermissionBiz sysButtonPermissionBiz;
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public SysUser loadSysUser(Long userId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public SysUser getSysUserByUsername(PageData pageData) {
        // TODO Auto-generated method stub
        try {
            return sysUserDao.getSysUserByUsername(pageData);
        } catch (Exception e) {
            logger.error("获取用户信息失败",e);
            throw new ShuxRunTimeException("获取用户信息失败",e);
        }
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        try {
            sysUserDao.updateSysUser(sysUser);
        } catch (Exception e) {
            logger.error("更新用户信息失败",e);
            throw new ShuxRunTimeException("更新用户信息失败",e);
        }
        
    }

    @Override
    public SysUser getUserAndRoleById(String userId) {
        try {
            return sysUserDao.getUserAndRoleById(userId);
        } catch (Exception e) {
            logger.error("通过用户ID获得用户及角色异常",e);;
            throw new ShuxRunTimeException("通过用户ID获得用户及角色异常",e);
        }
    }
    
    public Map<String,String> queryUserButtonAuth(String username){

        PageData pd = new PageData();
        Map<String, String> map = new HashMap<String, String>();
        try {
          pd.put("userName", username);
          String roleId = getSysUserByUsername(pd).getRoleId();
          pd.put("ROLE_ID", roleId);// 获取角色ID
          SysRole sysrole = sysRoleBiz.loadSysRole(roleId); // 获取角色信息
          map.put(Constant.OPERATOR_ADD, sysrole.getAddAuth()); // 增
          map.put(Constant.OPERATOR_DELETE, sysrole.getDelAuth()); // 删
          map.put(Constant.OPERATOR_EDIT, sysrole.getEditAuth()); // 改
          map.put(Constant.OPERATOR_QUERY, sysrole.getQueryAuth()); // 查
          List<SysButtonPermission> buttonQXnamelist = new ArrayList<SysButtonPermission>();
          if ("admin".equals(username)) {
            buttonQXnamelist = sysButtonPermissionBiz.queryAll(); // admin用户拥有所有按钮权限
          } else {
            buttonQXnamelist = sysButtonPermissionBiz.queryButtonByRole(roleId); // 此角色拥有的按钮权限标识列表
          }
          if(buttonQXnamelist != null){
              buttonQXnamelist.forEach((button)->{
                  map.put(button.getPreName(), UserConstant.BUTTON_PERMISSION); // 按钮权限
              });
          }
        } catch (Exception e) {
          logger.error(e.toString(), e);
        }
        return map;
      
    }
    
    /**
     * 更新登录用户的IP
     * 
     * @param USERNAME
     * @throws Exception
     */
    public void updateUserIp(String userId,HttpServletRequest request) {
      String ip = "";
      if (request.getHeader("x-forwarded-for") == null) {
        ip = request.getRemoteAddr();
      } else {
        ip = request.getHeader("x-forwarded-for");
      }
      SysUser sysUser = new SysUser();
      sysUser.setUsername(userId);
      sysUser.setIp(ip);
      updateSysUser(sysUser);
    }
    
    
}
